package com.codefalse.mybatis.generator.util;

import com.codefalse.mybatis.generator.model.ConfigModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;

import javax.sql.DataSource;
import javax.xml.crypto.Data;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author songxiangfeng
 * Created At 2020-01-20 17:11
 */
@Slf4j
public class ConnectionUtils {

    public static String testConnection(ConfigModel configModel) {
        DataSource dataSource = buildDataSource(configModel);
        try {
            Connection connection = dataSource.getConnection();
            if (connection == null) {
                return "连接失败";
            }
            connection.close();
            return "连接成功!";
        } catch (SQLException e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    private static DataSource buildDataSource(ConfigModel configModel) {
        return DataSourceBuilder.create().type(SingleConnectionDataSource.class)
                .driverClassName("com.mysql.jdbc.Driver")
                .url(configModel.packageJDBCUrl())
                .username(configModel.getUsername())
                .password(configModel.getPassword())
                .build();
    }

}
